<template>
  <div id="zybmInfo-container">
    <el-button type="primary" @click="handleBack">返回</el-button>
    <div class="bottom">
      <h4>编目信息</h4>
      <el-form
        ref="formRef"
        :label-position="labelPosition"
        :model="formData"
        :rules="rules"
        class="bottomCon"
        :disabled="isViewMode"
      >
        <!-- 基本信息区域 -->
        <div class="section">
          <div class="title">
            <div class="word">基本信息</div>
            <div class="line"/>
          </div>

          <!-- 信息资源分类 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="信息资源分类：" prop="dataNodes" class="form-item">
                <treeselect
                  v-model="formData.dataNodes"
                  :flat="true"
                  :multiple="true"
                  :options="treeData"
                  :disable-branch-nodes="true"
                  :clearable="true"
                  placeholder="请选择（可多选子项）"
                  :disabled="isViewMode"
                  :loading="isLoading"
                  class="form-control"
                  @select="handleSelect"
                  @deselect="handleDeselect"
                >
                  <div slot="value-label" slot-scope="{ node }">{{ node.raw.label }}</div>
                </treeselect>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 编目名称 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="编目名称：" prop="catalogName" class="form-item">
                <el-input
                  v-model="formData.catalogName"
                  placeholder="编目名称"
                  :disabled="isViewMode"
                  maxlength="64"
                  class="form-control"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 信息资源提供方 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="信息资源提供方：" prop="dataSource" class="form-item">
                <el-select v-model="formData.dataSource" filterable placeholder="请选择" clearable class="form-control">
                  <el-option v-for="item in providerOptions" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 信息资源摘要 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="信息资源摘要：" prop="catalogDescription" class="form-item">
                <el-input v-model="formData.catalogDescription" placeholder="请输入" maxlength="64"
                          class="form-control"/>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 更新周期 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="更新周期：" prop="updateCycle" class="form-item">
                <el-select v-model="formData.updateCycle" placeholder="请选择" class="form-control">
                  <el-option v-for="item in zqArr" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 数据分级 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="数据分级：" prop="dataClassification" class="form-item">
                <el-select v-model="formData.dataClassification" placeholder="请选择" class="form-control">
                  <el-option v-for="item in sjfjList" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 数据资源选择行：新增已选资源回显 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="数据资源：" prop="dataResources" class="form-item">
                <el-button type="text" @click="djsjzy">点击选择数据资源</el-button>
                <!-- 回显已选资源名称 -->
                <div v-if="formData.dataResources && formData.dataResources.length > 0" class="selected-resource-text">
                  已选：{{ formData.dataResources.map(r => r.resourceName).join('、') }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 数据量 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="数据量（条数）：" prop="dataVolume" class="form-item">
                <!-- <el-input v-model.number="formData.dataVolume" placeholder="请输入" maxlength="64" type="number"
                  class="form-control" /> -->

                <el-input
                  v-model="formData.dataVolume"
                  placeholder="请输入"
                  style="width:250px"
                  controls-position="right"
                  @input="handleInputVolume"
                  @blur="handleBlurVolume"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 数据时间范围 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="数据时间范围：" prop="dateRange" class="form-item">
                <div class="date-range-container">
                  <el-date-picker
                    v-model="formData.dataBeginTime"
                    type="year"
                    placeholder="开始年份"
                    value-format="yyyy"
                    class="date-picker-item"
                    @change="beginTimeChange"
                  />
                  <span class="date-separator">-</span>
                  <el-date-picker
                    v-model="formData.dataEndTime"
                    type="year"
                    placeholder="结束年份"
                    value-format="yyyy"
                    class="date-picker-item"
                    :picker-options="pickerOptions"
                    @change="endTimeChange"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 政务数据提供方 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="政务数据提供方：" prop="governmentDataProvider" class="form-item">
                <el-input
                  v-model="formData.governmentDataProvider"
                  :disabled="true"
                  placeholder="请输入"
                  maxlength="64"
                  class="form-control"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="数据所在层级：" prop="dataLevel" class="form-item">
                <el-select v-model="formData.dataLevel" placeholder="请选择数据所在层级" class="form-control">
                  <el-option
                    v-for="item in dataLevelOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 资源弹窗 -->
        <el-dialog
          append-to-body
          :close-on-click-modal="false"
          :visible.sync="mountDialogVisible"
          title="选择资源进行挂载"
          width="1200px"
        >
          <div style="color: #606266; margin-bottom: 15px; font-size: 14px;">
            ⚠️ 提示：API资源仅支持单选，文件资源支持多选，且两种类型不能同时选择。
            <span v-if="selectedApiResource" style="color: #E6A23C; margin-left: 10px;">
      当前已选择API资源，无法选择文件资源
    </span>
            <span v-else-if="selectedFileResources.length > 0" style="color: #E6A23C; margin-left: 10px;">
      当前已选择{{ selectedFileResources.length }}个文件资源，无法选择API资源
    </span>
          </div>
          <!-- 1. 新增搜索条件区域 -->
          <div class="mount-search-container" style="margin-bottom: 15px;">
            <el-input
              v-model="mountQuery.resourceName"
              size="small"
              clearable
              placeholder="输入资源名称"
              style="width: 240px;"
              class="mount-filter-item"
              @keyup.enter.native="getMountResourceList"
            />
            <el-select
              v-model="mountQuery.resourceType"
              size="small"
              clearable
              placeholder="选择资源类型"
              style="width: 160px;"
              class="mount-filter-item"
              @change="getMountResourceList"
            >
              <el-option label="API" value="0"/>
              <el-option label="文件" value="1"/>
            </el-select>
            <!-- 1. 新增：请求方式筛选下拉框 -->
            <el-select
              v-model="mountQuery.resourceApiMethod"
              size="small"
              clearable
              placeholder="选择请求方式"
              style="width: 160px;"
              class="mount-filter-item"
              @change="getMountResourceList"
            >
              <el-option label="POST" value="0"/> <!-- 对应后端值0 -->
              <el-option label="GET" value="1"/> <!-- 对应后端值1 -->
            </el-select>
            <el-button size="small" type="primary" class="mount-filter-item" @click="getMountResourceList">
              搜索
            </el-button>
            <el-button size="small" class="mount-filter-item" @click="resetMountSearch">
              重置
            </el-button>
          </div>

          <!-- 2. 表格修改：删除type="selection"列，新增操作栏 -->
          <el-table
            ref="resourceTable"
            highlight-current-row
            style="width: 100%;"
            :data="resourceList"
            border
            @selection-change="handleSelectionChange"
          >
            <!-- 添加单选复选框列 -->
            <el-table-column type="selection" width="55" :selectable="handleSelectable"/>
            <el-table-column prop="resourceName" label="资源名称" width="200"/>
            <el-table-column label="资源类型" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.resourceType === '0'">API</span>
                <span v-if="scope.row.resourceType === '1'">文件</span>
              </template>
            </el-table-column>
            <el-table-column prop="resourceSm" label="资源说明" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ truncateString(scope.row.resourceSm, 50) }}
              </template>
            </el-table-column>
            <el-table-column label="详细信息" width="300">
              <template slot-scope="scope">
                <div v-if="scope.row.resourceType === '0'">
                  <div>URL: {{ truncateString(scope.row.resourceApiUrl, 100) || '-' }}</div>
                  <div>请求方式: {{ scope.row.resourceApiMethod === '0' ? 'POST' : 'GET' }}</div>
                </div>
                <div v-if="scope.row.resourceType === '1'">
                  <div>文件格式: {{ truncateString(scope.row.resourceFileType, 50) || '-' }}</div>
                  <div>文件路径: {{ truncateString(scope.row.resourceFilePath, 100) || '-' }}</div>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 3. 新增分页组件 -->
          <div class="mount-pagination-container" style="margin-top: 15px; text-align: right;">
            <el-pagination
              background
              layout="prev, pager, next, total"
              :total="mountTotalCount"
              :page-size="mountPageSize"
              :current-page="displayPage"
              @current-change="handleMountPageChange"
            />
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="mountDialogVisible = false">取消</el-button>
            <!-- 添加确认挂载按钮 -->
            <el-button type="primary" @click="confirmMount">
              确认挂载
            </el-button>
          </div>
        </el-dialog>
        <!-- 共享信息区域 -->
        <div class="section">
          <div class="title">
            <div class="word">共享信息</div>
            <div class="line"/>
          </div>

          <!-- 共享类型 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="共享类型：" prop="sharedType" class="form-item">
                <el-select v-model="formData.sharedType" placeholder="请选择" class="form-control"
                           @change="handleGxType">
                  <el-option label="无条件共享" value="0"/>
                  <el-option label="有条件共享" value="1"/>
                  <el-option label="不予共享" value="2"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 共享条件 -->
          <el-row v-if="formData.sharedType === '1'" class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="共享条件：" prop="sharedCondition" class="form-item">
                <el-input v-model="formData.sharedCondition" placeholder="请输入内容" maxlength="64"
                          class="form-control"/>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 共享方式分类 -->
          <!--          <el-row class="row-group">-->
          <!--            <el-col :span="24" class="col-item">-->
          <!--              <el-form-item label="共享方式分类：" prop="gxfsfl" class="form-item">-->
          <!--                <el-select v-model="formData.gxfsfl" placeholder="请选择" class="form-control">-->
          <!--                  <el-option v-for="item in shareTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
          <!--                </el-select>-->
          <!--              </el-form-item>-->
          <!--            </el-col>-->
          <!--          </el-row>-->

          <!-- 是否向社会开放 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="是否向社会开放：" prop="isPublic" class="form-item">
                <el-select v-model="formData.isPublic" placeholder="请选择" disabled class="form-control">
                  <el-option label="是" value="0"/>
                  <el-option label="否" value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 共享方式 -->
          <el-row class="row-group">
            <el-col :span="24" class="col-item">
              <el-form-item label="共享方式：" prop="shardWay" class="form-item">
                <el-radio-group v-model="formData.shardWay" class="radio-group">
                  <!-- 注释掉的数据库选项保持不变 -->
                  <!-- <el-radio label="0" class="radio-item">数据库</el-radio> -->
                  <el-radio label="0" class="radio-item">API服务</el-radio>
                  <el-radio label="1" class="radio-item">文件</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 数据项区域 -->
        <div class="section">
          <div class="title">
            <div class="word">数据项</div>
            <div class="line"/>
          </div>
          <!-- 新增提示文本 -->
          <div v-if="isDataItemsEmpty && !isViewMode" style="color: #F56C6C; margin-bottom: 15px; font-size: 14px;">
            ⚠️ 请至少添加一条数据项，否则无法保存
          </div>
          <el-button v-if="!isViewMode" style="margin-bottom: 20px;" @click="openAddItemDialog">新增数据项</el-button>
          <el-button
            v-if="!isViewMode"
            type="danger"
            size="small"
            :disabled="selectedItems.length === 0"
            @click="batchDeleteItems"
          >
            批量删除 ({{ selectedItems.length }})
          </el-button>
          <el-table :data="displayTableData" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column v-if="!isViewMode" type="selection" width="55"/>
            <el-table-column prop="itemName" label="数据项名称"/>
            <el-table-column prop="itemEnglishName" label="数据项英文名"/>
            <el-table-column prop="dataTypeLabel" label="数据类型"/>
            <el-table-column prop="dataLength" label="数据长度"/>
            <el-table-column prop="isDictLabel" label="是否有字典项"/>
            <!-- <el-table-column prop="sharedTypeLabel" label="共享类型" /> -->
            <el-table-column prop="isRequiredLabel" label="是否必填"/>
            <el-table-column v-if="!isViewMode" fixed="right" label="操作" width="150">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  style="margin-right: 10px;"
                  @click="editDataItem(scope.row)"
                >编辑
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  style="color: #F56C6C;"
                  @click="deleteDataItem(scope.$index, scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <Pagination
            :total-num="isEdit ? totalNum : localTotalNum"
            :current-page="currentPage"
            @handleCurrentChange="handleCurrentChange"
          />
        </div>

        <!-- 操作按钮 -->
        <div v-if="!isViewMode" class="btns">
          <el-button type="primary" @click="save(0)">保存</el-button>
          <el-button type="primary" @click="save(1)">保存并发布</el-button>
        </div>
      </el-form>
    </div>

    <!-- 新增数据项弹窗 -->
    <el-dialog
      v-if="!isViewMode"
      :title="isEditingItem ? '编辑数据项' : '新增数据项'"
      width="700px"
      :visible.sync="dialogFormVisibles"
    >
      <el-form
        ref="dataItemRef"
        :model="dataItemForm"
        :rules="dataItemRules"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="数据项名称" prop="itemName">
          <el-input v-model="dataItemForm.itemName" class="form-control"/>
        </el-form-item>
        <el-form-item label="数据项英文名" prop="itemEnglishName">
          <!-- <el-input v-model="dataItemForm.itemEnglishName" :maxlength="200" pattern="^[A-Za-z0-9_]*$"
            @input="handleInputEnglish" @paste="handlePaste" class="form-control" /> -->
          <el-input v-model="dataItemForm.itemEnglishName" :maxlength="200" class="form-control"/>
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <el-select v-model="dataItemForm.dataType" placeholder="请选择" class="form-control">
            <el-option label="字符串型" value="0"/>
            <el-option label="数值型N" value="1"/>
            <el-option label="货币型Y" value="2"/>
            <el-option label="日期型D" value="3"/>
            <el-option label="日期时间型T" value="4"/>
            <el-option label="逻辑型L" value="5"/>
            <el-option label="备注型M" value="6"/>
            <el-option label="通用型G" value="7"/>
            <el-option label="双精度型B" value="8"/>
            <el-option label="整型I" value="9"/>
            <el-option label="浮点型F" value="10"/>
            <el-option label="二进制blob" value="11"/>
            <el-option label="长文本text" value="12"/>
          </el-select>
        </el-form-item>
        <el-form-item label="数据长度" prop="dataLength">
          <!-- <el-input v-model="dataItemForm.dataLength" class="form-control" type="number" /> -->
          <el-input
            v-model="dataItemForm.dataLength"
            class="form-control"
            @input="handleInputDay"
            @blur="handleBlurDay"
          />
        </el-form-item>
        <el-form-item label="是否有字典项" prop="isDict">
          <el-select v-model="dataItemForm.isDict" placeholder="请选择" class="form-control">
            <el-option label="是" value="0"/>
            <el-option label="否" value="1"/>
          </el-select>
        </el-form-item>
        <!-- 新增或修改数据项时，数据项的共享类型应与数据编目的共享类型保持一致且无法修改，或直接隐藏该字段 -->
        <!-- <el-form-item label="共享类型" prop="sharedType">
          <el-select v-model="dataItemForm.sharedType" class="form-control">
            <el-option label="无条件共享" value="0" />
            <el-option label="有条件共享" value="1" />
            <el-option label="不予共享" value="2" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否必填" prop="isRequired">
          <el-select v-model="dataItemForm.isRequired" class="form-control">
            <el-option label="是" value="0"/>
            <el-option label="否" value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisibles = false">取消</el-button>
        <el-button type="primary" @click="addDataItem">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {getDataResource} from '@/api/resource/application'

import {
  getNodeSelect,
  getAlldept,
  getAddcatalog,
  updateCatalog,
  getAddcatalogitem,
  getSelectcatalogitemlist,
  getUpdatecatalogitem,
  getDelcatalogitem,
  getDelcatalogitemIds,
} from '@/api/zybm'
import Pagination from '@/components/common/Pagination.vue'

const defaultFormData = {
  dataNodes: [], // 信息资源分类
  catalogName: '', // 编目名称
  dataSource: '', // 信息资源提供方
  catalogDescription: '', // 信息资源摘要
  updateCycle: '', // 更新周期
  dataClassification: '', // 数据分级
  dataResources: [], // 数据资源
  dataVolume: '', // 数据量
  dataBeginTime: '', // 开始年份
  dataEndTime: '', // 结束年份
  governmentDataProvider: '沧州市数据局', // 政务数据提供方
  dataLevel: '',
  sharedType: '', // 共享类型
  sharedCondition: '', // 共享条件
  // gxfsfl: '', // 共享方式分类
  isPublic: '1', // 是否向社会开放
  shardWay: ''// 共享方式
}

export default {
  name: 'SjzyZybmInfo',
  components: {Pagination, Treeselect},
  data() {
    return {
      selectedApiResource: null, // 单独存储选中的API资源
      selectedFileResources: [], // 存储选中的文件资源
      selectedResourceIds: [],
      resourceList: [], // 表格数据源
      isProcessing: false, // 避免选择事件循环触发的标记
      selectedResources: [], // 选中的资源
      mountTotalCount: 0, // 资源总数
      mountCurrentPage: 0,
      mountPageSize: 10, // 每页条数
      mountDialogVisible: false,
      // 3. 新增挂载弹窗搜索条件
      mountQuery: {
        resourceName: '', // 资源名称搜索
        resourceType: '', // 资源类型筛选
        resourceApiMethod: ''
      },
      dataLevelOptions: [
        {value: 0, label: '国家级'},
        {value: 1, label: '省级'},
        {value: 2, label: '市级'},
        {value: 3, label: '县区级'}
      ],
      currentPage: 1, // 当前页（共用）
      pageSize: 10, // 每页条数（固定，可扩展为可配置）
      totalNum: 0, // 编辑状态：后端返回总条数
      localItems: [], // 新增状态：本地存储所有数据项
      localTotalNum: 0, // 新增状态：本地数据总条数
      isViewMode: false, // 新增查看模式标记
      isEdit: false, // 是否为编辑状态（true：修改，false：新增）
      editId: null, // 用于存储修改数据的ID
      selectedItems: [], // 存储选中的数据项
      isEditingItem: false, // 是否处于编辑状态
      currentEditIndex: -1, // 当前编辑项的索引
      labelPosition: 'right',
      // 表单数据
      formData: {
        ...defaultFormData,
        dataResources: []
      },

      // 数据项表单
      dataItemForm: {
        itemName: '',
        itemEnglishName: '',
        dataType: '',
        dataLength: '',
        isDict: '',
        sharedType: '',
        isRequired: ''
      },

      // 验证规则
      rules: {
        dataNodes: [{required: true, message: '请选择信息资源分类', trigger: 'change'}],
        catalogName: [{required: true, message: '请输入信息编目名称', trigger: 'blur'}],
        dataSource: [{required: true, message: '请选择信息资源提供方', trigger: 'change'}],
        catalogDescription: [{required: true, message: '请输入信息资源摘要', trigger: 'blur'}],
        updateCycle: [{required: true, message: '请选择更新周期', trigger: 'change'}],
        dataClassification: [{required: true, message: '请选择数据分级', trigger: 'change'}],
        dataResources: [{
          required: true,
          type: 'array', // 明确类型为数组
          message: '请选择数据资源',
          trigger: 'change'
        }],
        // dataVolume: [{ required: true, message: '请输入数据量', trigger: 'blur', type: 'number' }],
        dataBeginTime: [{required: true, message: '请选择开始年份', trigger: 'change'}],
        dataEndTime: [{required: true, message: '请选择结束年份', trigger: 'change'}],
        governmentDataProvider: [{required: true, message: '请输入政务数据提供方', trigger: 'blur'}],
        dataLevel: [{required: true, message: '请选择数据所在层级', trigger: 'change'}],
        sharedType: [{required: true, message: '请选择共享类型', trigger: 'change'}],
        sharedCondition: [{required: true, message: '请输入共享条件', trigger: 'blur'}],
        // gxfsfl: [{ required: true, message: '请选择共享方式分类', trigger: 'change' }],
        isPublic: [{required: true, message: '请选择是否向社会开放', trigger: 'change'}],
        shardWay: [{required: true, message: '请至少选择一种共享方式', trigger: 'change'}]
      },

      // 数据项验证规则
      dataItemRules: {
        itemName: [{required: true, message: '请输入数据项名称', trigger: 'blur'}],
        itemEnglishName: [{required: true, message: '请输入数据项英文名', trigger: 'blur'}],
        dataType: [{required: true, message: '请选择数据类型', trigger: 'change'}],
        // dataLength: [{ required: true, message: '请输入数据长度', trigger: 'blur', type: 'number' }],
        isDict: [{required: true, message: '请选择是否有字典项', trigger: 'change'}],
        sharedType: [{required: true, message: '请选择共享类型', trigger: 'change'}],
        isRequired: [{required: true, message: '请选择是否必填', trigger: 'change'}]
      },

      // 下拉选项数据
      zqArr: [
        {value: '0', label: '实时'},
        {value: '1', label: '每天'},
        {value: '2', label: '每周'},
        {value: '3', label: '每月'},
        {value: '4', label: '每季度'},
        {value: '5', label: '每半年'},
        {value: '6', label: '每年'},
        {value: '7', label: '其他'}

      ],
      sjfjList: [
        {value: '0', label: '一般数据'},
        {value: '1', label: '重要数据'},
        {value: '2', label: '核心数据'}
      ],
      shareTypeOptions: [
        {value: '0', label: '数据库共享'},
        {value: '1', label: 'API共享'},
        {value: '2', label: '文件共享'}
      ],
      // 数据类型映射表（用于表格显示文本）
      dataTypeMap: {
        '0': '字符串型',
        '1': '数值型N',
        '2': '货币型Y',
        '3': '日期型D',
        '4': '日期时间型T',
        '5': '逻辑型L',
        '6': '备注型M',
        '7': '通用型G',
        '8': '双精度型B',
        '9': '整型I',
        '10': '浮点型F',
        '11': '二进制blob',
        '12': '长文本text'
      },
      // 字典项状态映射
      isDictMap: {'0': '是', '1': '否'},
      // 共享类型映射
      sharedTypeMap: {'0': '无条件共享', '1': '有条件共享', '2': '不予共享'},
      // 是否必填映射
      isRequiredMap: {'0': '是', '1': '否'},

      // 其他数据
      treeData: [],
      isLoading: false,
      dialogFormVisibles: false,
      tableData: [],
      providerOptions: [], // 提供方可从接口获取
      pickerOptions: { // 数据时间范围

        shortcuts: [{
          text: '至今',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }]
      }
    }
  },
  computed: {
    // 计算当前页显示的数据（区分新增/编辑状态）
    displayTableData() {
      if (this.isEdit) {
        // 编辑状态：直接使用后端返回的分页数据
        return this.tableData
      } else {
        // 新增状态：从本地数据中截取当前页数据
        const start = (this.currentPage - 1) * this.pageSize
        const end = start + this.pageSize
        return this.localItems.slice(start, end)
      }
    },
    // 新增：判断数据项列表是否为空
    isDataItemsEmpty() {
      if (this.isEdit) {
        // 编辑状态：判断后端返回的表格数据是否为空
        return this.tableData.length === 0
      } else {
        // 新增状态：判断本地存储的所有数据项是否为空
        return this.localItems.length === 0
      }
    },
    // 计算显示在分页组件上的页码（从1开始）
    displayPage() {
      return this.mountCurrentPage + 1
    }
  },
  created() {
    this.loadTreeData()
    this.loadProviders() // 加载提供方数据
    // 初始化时重置为新增状态
    this.resetForm()
  },
  methods: {
    // 截断超长字符串，超过长度时显示省略号
    truncateString(str, maxLength) {
      if (!str || typeof str !== 'string') return str;
      if (str.length <= maxLength) return str;
      return str.slice(0, maxLength) + '...';
    },
    // 确认挂载逻辑
    confirmMount() {
      const selectedResources = [];

      if (this.selectedApiResource) {
        selectedResources.push(this.selectedApiResource);
      }
      if (this.selectedFileResources.length > 0) {
        selectedResources.push(...this.selectedFileResources);
      }

      if (selectedResources.length === 0) {
        this.$message.warning('请至少选择一个资源');
        return;
      }

      // 验证选择是否符合规则
      const hasApi = selectedResources.some(item => item.resourceType === '0');
      const hasFile = selectedResources.some(item => item.resourceType === '1');

      if (hasApi && hasFile) {
        this.$message.warning('API资源和文件资源不能同时选择');
        return;
      }

      if (hasApi && selectedResources.length > 1) {
        this.$message.warning('API资源只能单选');
        return;
      }

      this.formData.dataResources = selectedResources;
      this.mountDialogVisible = false;
      this.$message.success('资源挂载成功');
    },
    handleMountPageChange(page) {
      // page是用户点击的显示页码（1,2,3...）
      const targetPage = page - 1 // 转换为后端需要的页码（0,1,2...）

      // 避免重复请求
      if (targetPage === this.mountCurrentPage) {
        return
      }

      this.mountCurrentPage = targetPage
      this.selectedResourceIds = []; // 翻页清空选中
      this.getMountResourceList()
    },
    djsjzy() {
      this.mountDialogVisible = true;

      // 重置选择状态
      this.selectedApiResource = null;
      this.selectedFileResources = [];

      // 根据已选资源初始化选择状态
      if (this.formData.dataResources && this.formData.dataResources.length > 0) {
        const apiResource = this.formData.dataResources.find(item => item.resourceType === '0');
        const fileResources = this.formData.dataResources.filter(item => item.resourceType === '1');

        if (apiResource) {
          this.selectedApiResource = apiResource;
        }
        if (fileResources.length > 0) {
          this.selectedFileResources = fileResources;
        }
      }

      this.getMountResourceList();
    },
    resetMountSearch() {
      this.mountQuery = {resourceName: '', resourceType: '', resourceApiMethod: ''}
      this.mountCurrentPage = 0 // 重置页码为第一页
      this.getMountResourceList()
    },

    getMountResourceList() {
      getDataResource({
        page: this.mountCurrentPage,
        size: this.mountPageSize,
        resourceName: this.mountQuery.resourceName || null,
        resourceType: this.mountQuery.resourceType || null,
        resourceApiMethod: this.mountQuery.resourceApiMethod || null
      }).then(res => {
        this.resourceList = res.content.map(item => ({
          ...item,
          resourceType: item.resourceType.toString(),
          resourceApiUrl: this.truncateString(item.resourceApiUrl, 200),
          resourceSm: this.truncateString(item.resourceSm, 500),
          resourceFilePath: this.truncateString(item.resourceFilePath, 200)
        }));

        // 数据加载完成后设置选中状态
        this.$nextTick(() => {
          this.setTableSelection();
        });
      });
    },
    setTableSelection() {
      if (this.$refs.resourceTable) {
        this.$refs.resourceTable.clearSelection();

        // 设置API资源选中
        if (this.selectedApiResource) {
          const apiRow = this.resourceList.find(item =>
            item.id === this.selectedApiResource.id && item.resourceType === '0'
          );
          if (apiRow) {
            this.$refs.resourceTable.toggleRowSelection(apiRow, true);
          }
        }

        // 设置文件资源选中
        if (this.selectedFileResources.length > 0) {
          this.selectedFileResources.forEach(selectedFile => {
            const fileRow = this.resourceList.find(item =>
              item.id === selectedFile.id && item.resourceType === '1'
            );
            if (fileRow) {
              this.$refs.resourceTable.toggleRowSelection(fileRow, true);
            }
          });
        }
      }
    },

    // 新增查看数据方法
    setViewData(row) {
      this.isViewMode = true // 标记为查看模式
      this.isEdit = false // 不是编辑模式

      // 数据处理与编辑模式类似
      const dataNodeIds = (row.dataNodes || []).map(item => item.id)

      const dataResources = row.dataResources || []

      // 回显表单数据
      this.formData = {
        dataNodes: dataNodeIds,
        catalogName: row.catalogName || '',
        dataSource: row.dataSource && row.dataSource.id ? row.dataSource.id : '',
        catalogDescription: row.catalogDescription || '',
        updateCycle: row.updateCycle != null ? row.updateCycle.toString() : '',
        dataClassification: row.dataClassification != null ? row.dataClassification.toString() : '',
        dataResources: dataResources,
        dataVolume: row.dataVolume || '',
        dataBeginTime: row.dataBeginTime || '',
        dataEndTime: row.dataEndTime || '',
        governmentDataProvider: row.governmentDataProvider || '沧州市数据局',
        dataLevel: row.dataLevel != null ? row.dataLevel : '',
        sharedType: row.sharedType != null ? row.sharedType.toString() : '',
        sharedCondition: row.sharedCondition || '',
        isPublic: row.isPublic != null ? row.isPublic.toString() : '',
        shardWay: row.shardWay != null ? row.shardWay.toString() : ''
      }

      // 修复数据项表格显示问题
      // 1. 确保使用正确的数据源存储数据项
      this.localItems = (row.catalogItems || []).map(item => ({
        ...item,
        // 转换数字类型字段为字符串，匹配映射表的键
        dataType: item.dataType != null ? item.dataType.toString() : '',
        isDict: item.isDict != null ? item.isDict.toString() : '',
        sharedType: item.sharedType != null ? item.sharedType.toString() : '',
        isRequired: item.isRequired != null ? item.isRequired.toString() : '',
        // 保留显示用的标签字段
        dataTypeLabel: this.dataTypeMap[item.dataType != null ? item.dataType.toString() : ''] || '未知类型',
        isDictLabel: this.isDictMap[item.isDict != null ? item.isDict.toString() : ''] || '未知',
        sharedTypeLabel: this.sharedTypeMap[item.sharedType != null ? item.sharedType.toString() : ''] || '未知',
        isRequiredLabel: this.isRequiredMap[item.isRequired != null ? item.isRequired.toString() : ''] || '未知'
      }))

      // 2. 初始化查看模式下的分页数据
      this.localTotalNum = this.localItems.length
      this.currentPage = 1

      // 3. 确保表格使用正确的计算属性
      // （模板中表格已绑定displayTableData，这里无需额外处理）
    },
    // 重置表单为新增状态
    resetForm() {
      this.isViewMode = false
      this.isEdit = false
      this.editId = null
      this.formData = {
        ...defaultFormData
        // dataNodes: [],
        // catalogName: '',
        // dataSource: '',
        // shardWay: []
        // ... 其他字段重置为初始值
      }
      // 重置本地分页数据
      this.localItems = []
      this.localTotalNum = 0
      this.currentPage = 1
      // 清空表单验证状态
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
    },
    // 接收父组件传递的修改数据并回显
    setEditData(row) {
      this.isViewMode = false
      this.isEdit = true // 标记为编辑状态
      this.editId = row.id // 保存当前修改数据的ID（接口需要）
      // 关键修复：从对象数组中提取id组成新数组
      const dataNodeIds = (row.dataNodes || []).map(item => item.id)

      // 回显表单数据（字段名需与row保持一致，不一致需映射）
      this.formData = {
        dataNodes: dataNodeIds, // 信息资源分类（需与树形组件格式匹配）
        catalogName: row.catalogName || '', // 编目名称
        dataSource: row.dataSource && row.dataSource.id ? row.dataSource.id : '', // 信息资源提供方
        catalogDescription: row.catalogDescription || '', // 信息资源摘要
        updateCycle: row.updateCycle != null ? row.updateCycle.toString() : '',
        dataClassification: row.dataClassification != null ? row.dataClassification.toString() : '',
        dataResources: row.dataResources || [],
        dataVolume: row.dataVolume || '', // 数据量
        dataBeginTime: row.dataBeginTime || '', // 开始年份
        dataEndTime: row.dataEndTime || '', // 结束年份
        governmentDataProvider: row.governmentDataProvider || '沧州市数据局', // 政务数据提供方
        sharedType: row.sharedType != null ? row.sharedType.toString() : '',
        sharedCondition: row.sharedCondition || '', // 共享条件
        // gxfsfl: row.gxfsfl != null ? row.gxfsfl.toString() : '',
        isPublic: row.isPublic != null ? row.isPublic.toString() : '',
        shardWay: row.shardWay != null ? row.shardWay.toString() : '',
        dataLevel: row.dataLevel != null ? row.dataLevel : ''
      }
      // 关键修复：处理数据项（catalogItems）回显
      console.log('后端返回的catalogItems数据：', row.catalogItems) // 调试用，确认数据存在
      // 替换这部分代码
      this.tableData = (row.catalogItems || []).map(item => ({
        ...item, // 保留原始字段（id、itemName等）
        // 转换数字类型字段为字符串，匹配映射表的键（避免类型不匹配）
        dataTypeLabel: this.dataTypeMap[item.dataType != null ? item.dataType.toString() : ''] || '未知类型',
        isDictLabel: this.isDictMap[item.isDict != null ? item.isDict.toString() : ''] || '未知',
        sharedTypeLabel: this.sharedTypeMap[item.sharedType != null ? item.sharedType.toString() : ''] || '未知',
        isRequiredLabel: this.isRequiredMap[item.isRequired != null ? item.isRequired.toString() : ''] || '未知'
      }))
      // 初始化编辑状态分页
      this.currentPage = 1
      this.getCatalogItemList() // 加载第一页数据
    },
    // 加载树形数据
    loadTreeData() {
      this.isLoading = true
      getNodeSelect().then(res => {
        if (res && res.CMeunDepts) {
          this.treeData = this.transformTreeData(res.CMeunDepts)
        }
      }).finally(() => {
        this.isLoading = false
      })
    },

    // 转换树形数据格式
    transformTreeData(rawData) {
      return rawData.filter(level1 => level1.id && level1.CMeunDepts && level1.CMeunDepts.length)
        .map(level1 => ({
          id: level1.id,
          label: level1.name,
          children: level1.CMeunDepts
            .filter(level2 => level2.id && level2.name)
            .map(level2 => ({
              id: level2.id,
              label: level2.name
            }))
        }))
    },

    // 加载提供方数据
    loadProviders() {
      getAlldept().then(res => {
        console.log(res, '信息资源提供方')
        this.providerOptions = res
      })
      // 实际项目中从接口获取
    },

    // 共享类型变更处理
    handleGxType(val) {
      // 当共享类型不是有条件共享时清空共享条件
      if (val !== '1') {
        this.formData.sharedCondition = ''
      }
    },

    // 新增数据项按钮点击
    openAddItemDialog() {
      this.resetDataItemForm()
      this.dialogFormVisibles = true
    },

    // 编辑数据项
    editDataItem(row) {
      this.isEditingItem = true
      if (this.isEdit) {
        this.currentEditIndex = this.tableData.findIndex(item => item.id === row.id)
      } else {
        this.currentEditIndexInLocal = this.localItems.findIndex(item => item.id === row.id)
      }
      // 回显表单数据
      const {...formData} = row
      // 将数字类型的字段转换为字符串，与下拉选项value类型匹配
      this.dataItemForm = {
        ...formData,
        dataType: formData.dataType != null ? formData.dataType.toString() : '',
        isDict: formData.isDict != null ? formData.isDict.toString() : '',
        sharedType: formData.sharedType != null ? formData.sharedType.toString() : '',
        isRequired: formData.isRequired != null ? formData.isRequired.toString() : ''
      }
      this.dialogFormVisibles = true
    },

    // 新增/编辑数据项
    addDataItem() {
      this.$refs.dataItemRef.validate(valid => {
        if (valid) {
          // 准备接口参数
          const params = {
            ...this.dataItemForm,
            catalogId: this.editId, // 关联当前编目ID
            // 转换数据类型为数字（根据后端要求调整）
            dataType: Number(this.dataItemForm.dataType),
            isDict: Number(this.dataItemForm.isDict),
            sharedType: Number(this.dataItemForm.sharedType),
            isRequired: Number(this.dataItemForm.isRequired),
            dataLength: this.dataItemForm.dataLength ? Number(this.dataItemForm.dataLength) : null
          }
          // 如果是编辑状态（修改编目），调用接口保存
          if (this.isEdit) {
            // 编辑状态
            if (this.isEditingItem) {
              // 修改数据项：调用更新接口
              getUpdatecatalogitem(params)
                .then(() => {
                  this.$message.success('数据项更新成功')
                  this.getCatalogItemList() // 刷新当前页
                  this.resetDataItemForm()
                  this.dialogFormVisibles = false
                })
                .catch(() => this.$message.error('更新失败'))
            } else {
              // 调用接口
              getAddcatalogitem(params).then(res => {
                this.$message.success('数据项添加成功')
                // 新增成功后调用查询接口刷新列表
                this.getCatalogItemList()
                // 关闭弹窗并重置表单
                this.resetDataItemForm()
                this.dialogFormVisibles = false
              })
            }
          } else {
            // 先判断是否存在重复数据项名称
            const itemName = this.dataItemForm.itemName
            const itemEnglishName = this.dataItemForm.itemEnglishName
            console.log('localItems', this.localItems, itemName)
            const itemNameList = this.localItems.filter(item => {
              return item.itemName === itemName
            })
            const itemEnglishNameList = this.localItems.filter(item => {
              return item.itemEnglishName === itemEnglishName
            })
            if (itemNameList.length > 0) {
              this.$message.warning(`数据项中文名称《${itemName}》已经存在，请输入其他数据项名称！`)
              return
            }
            if (itemEnglishNameList.length > 0) {
              this.$message.warning(`数据项英文名称《${itemEnglishName}》已经存在，请输入其他数据项名称！`)
              return
            }
            const newItem = {
              ...this.dataItemForm,
              dataTypeLabel: this.dataTypeMap[this.dataItemForm.dataType],
              isDictLabel: this.isDictMap[this.dataItemForm.isDict],
              sharedTypeLabel: this.sharedTypeMap[this.dataItemForm.sharedType],
              isRequiredLabel: this.isRequiredMap[this.dataItemForm.isRequired],
              id: this.isEditingItem ? this.localItems[this.currentEditIndexInLocal].id : Date.now()
            }

            if (this.isEditingItem) {
              // 编辑本地数据项
              this.localItems.splice(this.currentEditIndexInLocal, 1, newItem)
            } else {
              this.localItems.push(newItem)
            }
            this.localTotalNum = this.localItems.length // 更新总条数
            this.$message.success(this.isEditingItem ? '更新成功' : '添加成功')
            this.resetDataItemForm()
            this.dialogFormVisibles = false
          }
        }
      })
    },

    // 添加查询数据项列表的方法
    getCatalogItemList() {
      // 调用查询接口
      const param = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        catalogId: this.editId
      }
      getSelectcatalogitemlist(param)
        .then(res => {
          console.log(res, '0000')
          this.totalNum = res.totalElements
          // 转换数据格式适配表格显示
          this.tableData = res.content.map(item => ({
            ...item,
            dataTypeLabel: this.dataTypeMap[item.dataType != null ? item.dataType.toString() : ''] || '未知类型',
            isDictLabel: this.isDictMap[item.isDict != null ? item.isDict.toString() : ''] || '未知',
            sharedTypeLabel: this.sharedTypeMap[item.sharedType != null ? item.sharedType.toString() : ''] || '未知',
            isRequiredLabel: this.isRequiredMap[item.isRequired != null ? item.isRequired.toString() : ''] || '未知'
          }))
        })
        .catch(err => {
          console.error('查询数据项列表失败', err)
          this.$message.error('查询数据项失败，请重试')
        })
    },

    handleCurrentChange(val) {
      this.currentPage = val
      if (this.isEdit) {
        this.getCatalogItemList() // 编辑状态：请求新页数据
      }
    },

    // 重置数据项表单
    resetDataItemForm() {
      this.dataItemForm = {
        itemName: '',
        itemEnglishName: '',
        dataType: '',
        dataLength: '',
        isDict: '',
        sharedType: '',
        isRequired: ''
      }
      this.isEditingItem = false
      this.currentEditIndex = -1
      this.$nextTick(() => {
        this.$refs.dataItemRef && this.$refs.dataItemRef.clearValidate()
      })
    },

    // 保存表单
    save(type) {
      // 先判断数据项是否为空
      if (this.isDataItemsEmpty) {
        this.$message.warning('请至少添加一条数据项后再进行保存操作')
        return // 阻止后续操作
      }
      this.$refs.formRef.validate(valid => {
        if (valid) {
          // 处理共享条件非必填场景
          if (this.formData.sharedType !== '0') {
            valid = true
          }

          if (valid) {
            const params = {
              ...this.formData,
              dataNodes: this.formData.dataNodes, // 转换回对象数组
              dataSource: this.formData.dataSource,
              // 处理数据项：仅保留后端需要的字段（过滤显示用的Label字段）
              catalogItems: this.isEdit ? [] : this.localItems.map(item => {
                const { ...realData } = item
                return realData
              }),
              shardWay: Number(this.formData.shardWay),
              id: this.isEdit ? this.editId : null, // 修改时必须传递id
              operation: type // 0-保存 1-保存并发布
            }

            // 根据状态调用不同接口
            const requestFn = this.isEdit ? updateCatalog : getAddcatalog

            requestFn(params).then(res => {
              console.log(this.isEdit ? '修改成功' : '新增成功', res)
              this.$message.success(this.isEdit ? '修改成功' : '保存成功')
              // 成功后返回列表页
              this.handleBack()
            }).catch(err => {
              console.error(this.isEdit ? '修改失败' : '新增失败', err)
              this.$message.error('操作失败，请重试')
            })
          }
        }
      })
    },

    // 返回
    handleBack() {
      this.$emit('isShowHandle') // 返回上一页
    },

    // 选择事件处理
    handleSelect() {
    },
    handleDeselect() {
    },

    handleSelectionChange(selection) {
      if (this.isProcessing) {
        this.isProcessing = false;
        return;
      }

      this.isProcessing = true;

      // 分析当前选择
      const selectedApiRows = selection.filter(row => row.resourceType === '0');
      const selectedFileRows = selection.filter(row => row.resourceType === '1');

      // 规则验证
      if (selectedApiRows.length > 0 && selectedFileRows.length > 0) {
        // 同时选择了API和文件，不允许
        this.$message.warning('API资源和文件资源不能同时选择');
        this.isProcessing = false;
        this.setTableSelection(); // 恢复到之前的选择状态
        return;
      }

      if (selectedApiRows.length > 1) {
        // 选择了多个API，不允许
        this.$message.warning('API资源只能单选');
        this.isProcessing = false;
        this.setTableSelection(); // 恢复到之前的选择状态
        return;
      }

      // 更新选择状态
      if (selectedApiRows.length > 0) {
        this.selectedApiResource = selectedApiRows[0];
        this.selectedFileResources = [];
      } else if (selectedFileRows.length > 0) {
        this.selectedApiResource = null;
        this.selectedFileResources = selectedFileRows;
      } else {
        // 清空选择
        this.selectedApiResource = null;
        this.selectedFileResources = [];
      }

      this.isProcessing = false;
    },


    // 优化：通过row的唯一标识（如id）判断选中行是否相同
    isSameSelection(arr1, arr2) {
      if (arr1.length !== arr2.length) return false;
      // 按id排序后对比，避免顺序不同导致误判
      const sorted1 = [...arr1].sort((a, b) => a.id - b.id).map(r => r.id);
      const sorted2 = [...arr2].sort((a, b) => a.id - b.id).map(r => r.id);
      return sorted1.join(',') === sorted2.join(',');
    },

    // 确保所有行都可被选择（文件行不被禁用）
    handleSelectable(row) {
      // 如果已经选择了API，不允许再选择文件，反之亦然
      if (this.selectedApiResource && row.resourceType === '1') {
        return false;
      }
      if (this.selectedFileResources.length > 0 && row.resourceType === '0') {
        return false;
      }

      // API只能单选
      if (row.resourceType === '0' && this.selectedApiResource) {
        return false;
      }

      return true;
    },
    // 删除数据项
    // 单个删除数据项
    deleteDataItem(index, row) {
      this.$confirm('确定删除该数据项吗？', '提示', {type: 'warning'})
        .then(() => {
          if (this.isEdit) {
            // 编辑状态：调用后端删除接口（假设接口为deleteCatalogItem）
            getDelcatalogitem(row.id)
              .then(() => {
                this.$message.success('删除成功')
                this.getCatalogItemList() // 刷新当前页
              })
              .catch(() => this.$message.error('删除失败'))
          } else {
            // 新增状态：本地删除
            const itemIndex = this.localItems.findIndex(item => item.id === row.id)
            if (itemIndex !== -1) {
              this.localItems.splice(itemIndex, 1)
              this.localTotalNum = this.localItems.length
              // 处理当前页为空的情况
              if (this.displayTableData.length === 0 && this.currentPage > 1) {
                this.currentPage--
              }
              this.$message.success('删除成功')
            }
          }
        })
        .catch(() => this.$message.info('已取消删除'))
    },
    // 批量删除数据项
    batchDeleteItems() {
      if (this.selectedItems.length === 0) {
        return this.$message.warning('请至少选择一项')
      }
      this.$confirm(`确定删除选中的${this.selectedItems.length}项？`, '提示', {type: 'warning'})
        .then(() => {
          const ids = this.selectedItems.map(item => item.id)
          if (this.isEdit) {
            // 编辑状态：调用批量删除接口（假设为batchDeleteCatalogItems）
            getDelcatalogitemIds(ids)
              .then(() => {
                this.$message.success('批量删除成功')
                this.getCatalogItemList() // 刷新当前页
                this.selectedItems = []
              })
              .catch(() => this.$message.error('删除失败'))
          } else {
            // 新增状态：本地批量删除
            this.localItems = this.localItems.filter(item => !ids.includes(item.id))
            this.localTotalNum = this.localItems.length
            // 处理当前页为空的情况
            if (this.displayTableData.length === 0 && this.currentPage > 1) {
              this.currentPage--
            }
            this.selectedItems = []
            this.$message.success('批量删除成功')
          }
        })
        .catch(() => this.$message.info('已取消删除'))
    },
    beginTimeChange(val) {
      console.log('val', val)
      if (this.formData.dataBeginTime > this.formData.dataEndTime && this.formData.dataEndTime > 1900) {
        this.$message.warning(`开始年份不能比${this.formData.dataEndTime}年大`)
        this.formData.dataBeginTime = ''
      }
    },
    endTimeChange(val) {
      console.log('val', val)
      if (this.formData.dataEndTime < this.formData.dataBeginTime && this.formData.dataBeginTime > 1900) {
        this.$message.warning(`结束年份不能比${this.formData.dataBeginTime}年小`)
        this.formData.dataEndTime = ''
      }
    },
    // 过滤非英文字符
    filterEnglish(str) {
      if (!str) return ''
      // 只保留英文字母（大小写）和空格
      return str.replace(/[^a-zA-Z ]/g, '')
    },
    handleInput(val) {
      // 过滤输入的内容
      const filtered = this.filterEnglish(val)
      this.dataItemForm.itemEnglishName = filtered
    },
    /**
     * 处理输入事件，过滤非正整数字符
     */
    handleInputVolume() {
      let value = this.formData.dataVolume

      if (!value) {
        return
      }

      // 1. 只保留数字字符（过滤所有非数字）
      value = value.replace(/[^\d]/g, '')

      // 2. 处理前导零（仅允许单个0，多个0时保留第一个）
      if (value.length > 1 && value.startsWith('0')) {
        value = '0'
      }

      // 更新值并同步到父组件
      this.formData.dataVolume = value
    },

    /**
     * 失去焦点时处理（确保符合正整数规则）
     */
    handleBlurVolume() {
      let value = this.formData.dataVolume

      if (!value) {
        return
      }

      // 转换为整数
      const intVal = parseInt(value, 10)

      // 处理最小值限制
      if (this.min !== null && intVal < this.min) {
        value = this.min.toString()
        this.$message.warning(`输入值不能小于${this.min}`)
      } else if (this.max !== null && intVal > this.max) {
        value = this.max.toString()
        this.$message.warning(`输入值不能大于${this.max}`)
      } else {
        value = intVal.toString()
      }

      // 更新最终值
      this.formData.dataVolume = value
    },
    handleInputDay() {
      let value = this.dataItemForm.dataLength

      if (!value) {
        this.$emit('input', '')
        return
      }
      // 1. 只保留数字字符（过滤所有非数字）
      value = value.replace(/[^\d]/g, '')

      // 2. 处理前导零（仅允许单个0，多个0时保留第一个）
      if (value.length > 1 && value.startsWith('0')) {
        value = '0'
      }

      // 更新值并同步到父组件
      this.dataItemForm.dataLength = value
    },

    /**
     * 失去焦点时处理（补全一位小数、验证范围）
     */
    handleBlurDay() {
      let value = this.dataItemForm.dataLength

      if (!value) {
        return
      }

      // 转换为整数
      const intVal = parseInt(value, 10)

      // 处理最小值限制
      if (this.min !== null && intVal < this.min) {
        value = this.min.toString()
        this.$message.warning(`输入值不能小于${this.min}`)
      } else if (this.max !== null && intVal > this.max) {
        value = this.max.toString()
        this.$message.warning(`输入值不能大于${this.max}`)
      } else {
        value = intVal.toString()
      }

      // 更新最终值
      this.dataItemForm.dataLength = value
    },
    handleInputEnglish() {
      this.dataItemForm.itemEnglishName = this.dataItemForm.itemEnglishName.replace(/[^A-Za-z0-9_]/g, '')
    },
    handlePaste(e) {
      // 获取粘贴的内容
      const pasteValue = e.clipboardData.getData('text')
      // 校验粘贴内容是否合法
      const isLegal = /^[A-Za-z0-9_]*$/.test(pasteValue)
      if (!isLegal) {
        e.preventDefault() // 阻止粘贴
        this.$message.warning('粘贴内容包含非法字符，仅允许英文、数字和下划线')
      }
    }

  }
}
</script>

<style lang="scss" scoped>
#zybmInfo-container {
  //max-width: 1200px; /* 限制最大宽度 */
  margin: 0 auto;
  /* 水平居中 */
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .bottom {
    margin-top: 20px;

    h4 {
      padding-left: 10px;
      border-left: 3px solid #224ad4;
      margin-bottom: 20px;
      font-size: 18px;
      color: #333;
    }
  }

  .section {
    margin-bottom: 30px;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fafafa;
  }

  .title {
    display: flex;
    align-items: center;
    margin-bottom: 25px;

    .word {
      font-weight: bold;
      font-size: 16px;
      color: #333;
    }

    .line {
      flex: 1;
      height: 1px;
      background-color: #e5e5e5;
      margin-left: 15px;
    }
  }

  /* 表单行样式 */
  .row-group {
    margin-bottom: 18px;
    display: flex;
    justify-content: center;
  }

  .col-item {
    padding: 0 15px;
    box-sizing: border-box;
    width: 100%;
  }

  /* 表单项统一样式 */
  .form-item {
    display: flex;
    margin-bottom: 18px;

    ::v-deep .el-form-item__label {
      width: 180px;
      text-align: right;
      padding-right: 20px;
      box-sizing: border-box;
      font-size: 14px;
      color: #606266;
      line-height: 40px;
    }

    ::v-deep .el-form-item__content {
      flex: 1;
      margin-left: 0 !important;
      max-width: 500px;
    }
  }

  /* 统一表单控件样式 */
  .form-control {
    width: 100% !important;
    max-width: 500px;
    box-sizing: border-box;

    &.el-input__inner,
    &.el-textarea__inner,
    &.el-select {
      height: 40px;
      line-height: 40px;
    }
  }

  /* 日期范围特殊样式 */
  .date-range-container {
    display: flex;
    align-items: center;
    width: 100%;
    max-width: 500px;

    .date-picker-item {
      flex: 1;
      min-width: 200px;

      & + .date-picker-item {
        margin-left: 10px;
      }
    }

    .date-separator {
      width: 20px;
      text-align: center;
      color: #999;
    }
  }

  /* 复选框组样式 */
  .checkbox-group {
    display: flex;
    gap: 30px;
    padding-top: 8px;

    .checkbox-item {
      display: flex;
      align-items: center;
      margin-right: 0;
    }
  }

  /* 按钮区域 */
  .btns {
    margin-top: 40px;
    text-align: center;

    .el-button {
      width: 120px;
      height: 40px;
      font-size: 14px;
      margin: 0 15px;
    }
  }

  /* 表格样式 */
  .el-table {
    margin-top: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;

    &::before {
      height: 0;
    }

    th {
      background-color: #f5f7fa;
    }
  }

  /* 弹窗表单样式 */
  .el-dialog {
    .el-form-item {
      margin-bottom: 22px;

      &__label {
        width: 120px;
        text-align: right;
        padding-right: 15px;
      }

      &__content {
        width: 300px;
      }
    }
  }

  /* 处理treeselect组件样式统一 */
  ::v-deep .vue-treeselect {
    width: 100% !important;
    max-width: 500px;

    &__control {
      height: 40px;
    }

    &__placeholder,
    &__single-value {
      line-height: 40px !important;
    }
  }

  /* 处理下拉框样式 */
  ::v-deep .el-select {
    width: 100%;
  }

}
</style>
